package com.sjtu.config;

import com.sjtu.exception.RoleNotEnoughException;
import com.sjtu.service.LoginTokenService;
import com.sjtu.web.vo.UserAccountVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * nerine
 * 2/2/2020
 */
@Configuration
public class OperatorHandlerFilter extends HandlerInterceptorAdapter {
    public static final String OPERATOR_ID = AdminHandlerFilter.OPERATOR_ID;

    @Autowired
    private LoginTokenService loginTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod;
        try {
            handlerMethod = (HandlerMethod) handler;
        }catch (Exception e) {
            return super.preHandle(request, response, handler);
        }
        Operator ann = handlerMethod.getMethod().getAnnotation(Operator.class);
        checkRole(ann, request);
        return true;
    }

    void checkRole(Operator ann, HttpServletRequest request) {
        if(ann == null) {
            return;
        }
        String userId = request.getHeader(OPERATOR_ID);
        if(StringUtils.isBlank(userId)) {
            fail("no operatorId header found");
        }
        UserAccountVo user = loginTokenService.findByUserId(userId);
        if(user == null) {
            fail("no user found");
        }
        if(user.isNotOperator()) {
            fail("role is not operator");
        }
    }

    private void fail(String reason) {
        throw new RoleNotEnoughException(reason);
    }
}
